from typing import Annotated
import aiofiles

from fastapi import APIRouter, File, UploadFile, Depends

from utils.write_to_db import write_statistic_to_db
from routers.users import oauth2_scheme

files_router = APIRouter()


@files_router.post("/uploadfile/")
async def upload_file(
    token: Annotated[str, Depends(oauth2_scheme)],
    file: UploadFile = File(...),
):
    """Загружает файл."""
    filename = file.filename
    async with aiofiles.open(f"download/{filename}", mode="wb") as buffer:
        contents = await file.read()  # async read
        await buffer.write(contents)
    await write_statistic_to_db(filename=filename)
    return {"msg": "Файл успешно загружен"}
